package com.github.hgkmail.hello.leetcode101.collection.priorityqueue;

import com.github.hgkmail.hello.leetcode101.base.ListNode;

import java.util.Comparator;
import java.util.PriorityQueue;

public class LC23MergeKSortedLists {
    //利用PriorityQueue来输出当前最小的节点，可以用来合并有序列表、求前k大。
    public ListNode mergeKLists(ListNode[] lists) {
        if (lists.length<=0) {
            return null;
        }
        PriorityQueue<ListNode> heap = new PriorityQueue<>(lists.length, new Comparator<ListNode>() {
            @Override
            public int compare(ListNode o1, ListNode o2) {
                return o1.val-o2.val;
            }
        });
        for (int i = 0; i < lists.length; i++) {
            ListNode curr = lists[i];
            while (curr!=null) {
                heap.offer(curr); //offer 入队
                curr = curr.next;
            }
        }
        //使用dummy节点，可以简化代码
        ListNode res = new ListNode(0);
        ListNode curr = res;
        while (!heap.isEmpty()) {
            curr.next = heap.poll();
            curr = curr.next;
        }
        if (curr!=null) {
            curr.next=null;
        }

        return res.next;
    }
}
